import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class QuestionGenerator {
  // 静态成员变量
  static List<Map<String, dynamic>> questions = [];
  static List<String> userAnswers = [];
  static List<TextEditingController> controllers = [];
  static int correctCount = 0;
  static int incorrectCount = 0;
  static int totalQuestions = 0;
  static int score = 0;

  // 静态获取题目方法
  static Future<List<Map<String, dynamic>>> generateQuestions(int questionCount, int type) async {
    await generateQuestionsFromApi(questionCount, type);
    print('\x1B[31m${questions.length}\x1B[0m');
    return questions;  // 返回题目
  }

  // 静态获取题目方法
  static Future<void> generateQuestionsFromApi(int questionCount, int type) async {
    const apiUrl = 'http://101.34.58.190:8080/express';
    final url = Uri.parse('$apiUrl?num=$questionCount&type=$type');
    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        // 提取 API 返回的数据
        final List<Map<String, dynamic>> newQuestions = [];
        final List<TextEditingController> newControllers = [];

        for (var item in data['expressVOs']) {
          newQuestions.add({
            "examinationId": data["examinationId"], // 从外部字段获取
            "expressId": item["id"],               // 从每个题目获取
            "express": item["express"],            // 题目表达式
          });
          newControllers.add(TextEditingController());
        }

        // 更新静态状态
        questions = newQuestions;
        controllers = newControllers;
        userAnswers = List.filled(questions.length, '');
        totalQuestions = questionCount;
        correctCount = 0;
        incorrectCount = 0;
      } else {
        throw Exception('Failed to load questions');
      }
    } catch (e) {
      print('获取题目失败: $e');
    }
  }

  // 静态方法：提交答案并计算得分
  static void submitAnswers() {
    correctCount = 0;
    incorrectCount = 0;

    for (int i = 0; i < questions.length; i++) {
      final String userAnswer = controllers[i].text.trim();
      if (userAnswer.isNotEmpty && userAnswer == questions[i]["answer"].toString()) {
        correctCount++;
      } else {
        incorrectCount++;
      }
    }

    score = correctCount * 2; // 每题得分为 2 分
  }

  // 静态方法：更新答案
  static void updateAnswer(int index, String value) {
    userAnswers[index] = value;
    controllers[index].text = value;
  }
}
